/*
 * 退格键.c
 * 
 */


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void sign_up(char* user,char* pwd)
{
	FILE* f=fopen("manage.txt","r+"); //修改文件内容，从指定位置修改，必须使用"r+"模式
	fseek(f,0l,SEEK_SET);printf("%ld\n",ftell(f));
	fprintf(f,"%s %s",user,pwd);
	fclose(f);
}

void sign_alter(char* user,char* pwd)//定长密码修改，变长不会写
{
	printf("%d %d %d\n",strlen(user),strlen(pwd),strlen(user)+strlen(pwd));
	char user_sys[10], pwd_sys[7];
	FILE* f=fopen("manage.txt","r+"); //修改文件内容，从指定位置修改，必须使用"r+"模式
	while(EOF != fscanf(f,"%s %s",user_sys,pwd_sys))
	{printf("请输入修改密码%ld\n",ftell(f));
		if(!(strcmp(user,user_sys)||strcmp(pwd,pwd_sys)))
		{
			printf("请输入修改密码%ld\n",ftell(f));
			fseek(f,-strlen(pwd),SEEK_CUR);
			//fputc('\0',f);//后面内容会全部消失
			char s[7];scanf("%s",s);
			fprintf(f,"%s",s);
			break;
		}
	}
	fclose(f);
}

char* invisible(char c[7]) 
{
	while(1){
	char ch;int i;
	ch = getchar();
	if((ch  == 127 || ch  == 8) && i>0)//当有键入时，按键delete或backspace时，删除一位
		{
				printf("\b");	//这里是删除一个，通过输出回撤符 /b，回撤一格，
				printf(" ");	//再显示空格符把刚才的*给盖住，
				printf("\b");	//然后再 回撤一格等待录入。	
				--i; //此时i指在空格处
		}
	else if(ch==10 || ch == 13)//当键入的为换行时
		{
				c[i] = '\0';//将字符串以'\0'结尾
				return c;
		}
	else{c[i]=ch;printf("*");++i;} //成功读取时
}
}


int main()
{
	char c[7],user[10],user_sys[10],pwd_sys[7];
	sign_alter("user1","999999");
	while(1){
		
		printf("账户名：");
		scanf("%s",user);
		while(getchar()!='\n');
		
		/*stty 是unix下的命令，可以改变并打印终端行设置*/
		system("stty -icanon"); //stty -icanon 设置一次性读完操作，如使用getchar()读操作，不需要按enter
		system("stty -echo"); //stty -echo 设置命令不被显示
		printf("输入密码:");

		strcpy(c,invisible(c));
			
		system("stty echo"); // stty echo 取消不显设置
		system("stty icanon"); //stty icanon 取消设置
		
		sign_up(user,c);
		
		FILE* f=fopen("manage.txt","r");printf("\n%ld",ftell(f));
		fscanf(f,"%s %s",user_sys,pwd_sys);
		if(!(strcmp(user,user_sys)||strcmp(c,pwd_sys))){printf("\n%ld",ftell(f));printf("1\n");return 0;}
		fscanf(f,"%s %s",user_sys,pwd_sys);
		if(!(strcmp(user,user_sys)||strcmp(c,pwd_sys))){printf("\n%ld",ftell(f));printf("2\n");return 0;}
		while(EOF != fscanf(f,"%s %s",user_sys,pwd_sys))
		if(!(strcmp(user,user_sys)||strcmp(c,pwd_sys))){printf("\n%ld",ftell(f));printf("3\n");return 0;}
		printf("\nenter error! try again!\n");
		fclose(f);
	}
	return 0;
}

